<template>
  <div class="app-container">
    <el-tabs
      v-model="activeName"
      type="card"
      @tab-click="handleClick"
      @tab-add="addTopNode"
      :addable="true"
    >
      <el-tab-pane v-for="t in tabs" :label="t.title" :name="t.code">
        <div>
          <el-input
            v-model="roleViewModel.RoleName"
            size="small"
            placeholder="角色名称"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="queryRole"
          />
          <el-button type="primary" size="small" @click="queryRole" icon="el-icon-search">查询</el-button>
          <el-button type="primary" size="small" @click="handleAddRole" icon="el-icon-plus">新增</el-button>
          <el-button type="primary" @click="refresh" size="small" icon="el-icon-refresh">刷新</el-button>
        </div>
        <el-table
          :data="rolesList"
          v-loading="loading"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          style="width: 100%;margin-top:30px;"
          border
          row-key="id"
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
          <el-table-column label="角色名称" prop="RoleName">
            <template slot-scope="scope">{{ scope.row.RoleName }}</template>
          </el-table-column>
          <el-table-column label="标识码" width="220" prop="Code">
            <template slot-scope="scope">{{ scope.row.Code }}</template>
          </el-table-column>
          <el-table-column label="创建时间" width="220" prop="CreateTime">
            <template slot-scope="scope">{{ scope.row.CreateTime | formatDateSec}}</template>
          </el-table-column>
          <el-table-column align="center" width="200" label="操作">
            <template slot-scope="scope">
              <!-- <el-button type="text" size="mini" @click="handleUser(scope)" icon="el-icon-user">用户</el-button> -->
              <el-button
                type="text"
                size="mini"
                @click="rolesetting(scope)"
                icon="el-icon-setting"
              >配置</el-button>
              <el-button type="text" size="mini" @click="handleEdit(scope)" icon="el-icon-edit">编辑</el-button>
              <el-button
                type="text"
                size="mini"
                @click="handleDelete(scope)"
                icon="el-icon-delete"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType==='edit'?'编辑角色':'新增角色'"
      :close-on-click-modal="false"
    >
      <el-form :model="role" :rules="rules" ref="role" label-width="100px" label-position="right">
        <el-form-item label="父级角色" prop="ParentID">
          <el-input v-model="role.ParentName" placeholder="父级角色" :disabled="true" />
        </el-form-item>
        <el-form-item label="角色名称" prop="RoleName">
          <el-input v-model="role.RoleName" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="role.Text"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="备注"
          />
        </el-form-item>
        <!-- <el-form-item label="菜单">
          <el-tree ref="tree" :data="routesData" :props="defaultProps" show-checkbox default-expand-all node-key="id"
            class="permission-tree" />
        </el-form-item>-->
        <div style="text-align:right">
          <el-button type="danger" @click="dialogVisible=false">取消</el-button>
          <el-button type="primary" @click="confirmRole('role')">确认</el-button>
        </div>
      </el-form>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogUserVisible"
      :title="role.RoleName"
      :close-on-click-modal="false"
      width="60%"
      top="3vh"
    >
      <div>
        <el-input
          v-model="userViewModel.UserName"
          size="small"
          placeholder="姓名"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="queryUser"
        />
        <el-input
          v-model="userViewModel.LoginName"
          size="small"
          placeholder="登录名"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="queryUser"
        />
        <el-input
          v-model="userViewModel.MobilePhone"
          size="small"
          placeholder="手机号"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="queryUser"
        />
        <el-button type="primary" @click="queryUser" size="small" icon="el-icon-search">查询</el-button>
        <el-button type="primary" @click="refreshUser" size="small" icon="el-icon-refresh">刷新</el-button>
      </div>
      <el-table
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="userList"
        style="width: 100%;margin-top:30px;"
        border
        @sort-change="sortChange"
        ref="multipleTable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="姓名" sortable="custom" prop="UserName">
          <template slot-scope="scope">{{ scope.row.UserName }}</template>
        </el-table-column>
        <el-table-column label="登录名" sortable="custom" prop="LoginName">
          <template slot-scope="scope">{{ scope.row.LoginName }}</template>
        </el-table-column>
        <el-table-column label="手机号" sortable="custom" prop="MobilePhone">
          <template slot-scope="scope">{{ scope.row.MobilePhone }}</template>
        </el-table-column>
      </el-table>
      <!-- 分页组件：https://element.eleme.cn/#/zh-CN/component/pagination -->
      <div class="block" style="float:right;margin-top:15px;" v-if="userViewModel.total>0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="userViewModel.page"
          :page-sizes="[10, 20, 30, 40,100]"
          :page-size="userViewModel.pageSize"
          @prev-click="lastPage"
          @next-click="nextPage"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="userViewModel.total"
        ></el-pagination>
      </div>
      <div style="text-align:right;margin-top: 60px;">
        <el-button type="danger" @click="dialogUserVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRoleUser">确认</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogMenuVisible"
      :close-on-click-modal="false"
      :title="'新增'"
      width="60%"
      top="10vh"
    >
      <el-form
        ref="model"
        :rules="menuRules"
        :label-position="labelPosition"
        :model="model"
        label-width="100px"
        style="width: 90%;"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="菜单名称" prop="title">
              <el-input v-model="model.title" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜单路由" prop="path">
              <el-input v-model="model.path" placeholder="请输入菜单路由" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单重定向" prop="redirect">
              <el-input v-model="model.redirect" placeholder="请输入重定向" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序号" prop="sort">
              <el-input-number v-model="model.sort" style="width: 100%;"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-select
                v-model="model.type"
                class="filter-item"
                placeholder="请输入资源请求类型"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item"
                  :label="item | typeFilter"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜单图标" prop="icon">
              <el-input v-model="model.meta.icon" placeholder="请输入图标名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组件地址" prop="component">
              <el-input v-model="model.component" placeholder="组件地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                :autosize="{ minRows: 4, maxRows: 9}"
                v-model="model.remark"
                type="textarea"
                placeholder="备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogMenuVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmModel">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from "path";
import { deepClone } from "@/utils";
import {
  getRoutes,
  getRoleList,
  addRole,
  deleteRole,
  updateRole,
  getRoleUser,
  handleRoleUser
} from "@/api/role";
import { getUserList } from '@/api/user'
import { getPlatformList, addMenu } from "@/api/menu"

const defaultRole = {
  id: "",
  RoleName: "",
  ParentID: "",
  ParentName: "",
  RoleAuthorizationType: "",
  Type: '',
  Code: "",
  Text: "",
  routes: [],
  MenuIdList: [],
  HalfMenuIdList: [],
  FullMenuIdList: []
};

const defaultModel = {
  id: "",
  parentId: "",
  parentName: "",
  component: "",
  name: "",
  title: "",
  code: "",
  type: 1,
  path: "",
  redirect: "",
  sort: 0,
  hasChildren: false,
  meta: {
    title: "",
    roles: [
    ],
    affix: "",
    nocache: "",
    icon: ""
  },
  hidden: false,
  children: [
  ]
};

export default {
  filters: {
    typeFilter(type) {
      const typeMap = {
        1: '菜单',
        2: '按钮'
      }
      return typeMap[type]
    }
  },
  data() {
    return {
      role: Object.assign({}, defaultRole),
      roleUser: Object.assign({}, defaultRole),
      model: Object.assign({}, defaultModel),
      routes: [],
      rolesList: [],
      userList: [],
      typeOptions: [1, 2],
      activeName: 'USER',
      typeList: [
        { value: 'USER', label: '用户' },
        { value: 'TEACHER', label: '讲师' },
        { value: 'STUDENT', label: '学生' }
      ],
      multipleSelection: [],
      dialogVisible: false,
      dialogUserVisible: false,
      dialogMenuVisible: false,
      dialogType: "new",
      checkStrictly: true,
      labelPosition: "right",
      loading: true,
      defaultProps: {
        children: "children",
        label: "title"
      },
      userViewModel: {
        page: 1,
        pageSize: 10,
        total: 0,
        UserName: '',
        LoginName: '',
        MobilePhone: '',
        UserType: '',
        OrderBy: 'UserID',//排序字段
        SortDir: '' //是否升序
      },
      roleViewModel: {
        page: 1,
        pageSize: 10,
        total: 0,
        RoleName: '',
        OrderBy: 'CreateTime',
        IsAsc: '',
        Type: 'USER'
      },
      tabs: [],
      menuRules: {
        title: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
        component: [{ required: true, message: "请输入组件地址", trigger: "blur" }],
        path: [{ required: true, message: "请输入菜单路由", trigger: "blur" }]
      },
      rules: {
        RoleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur"
          }
        ],
        RoleAuthorizationType: [
          { required: true, message: "请输入角色类型", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    routesData() {
      return this.routes;
    }
  },
  mounted() {
    this.getPlatformList()
  },
  created() {
    // Mock: get all routes and roles list from server
    // this.getRoutes();
    // this.queryRole();
    this.refreshUser()
  },
  methods: {
    async getPlatformList() {
      var res = await getPlatformList()
      if (res.code == 200) {
        this.tabs = res.data
        this.activeName = this.tabs[0].code
        this.roleViewModel.Type = this.activeName
        this.queryRole()
      }
    },
    handleClick(tab, event) {
      this.roleViewModel.Type = this.activeName
      this.queryRole()
    },
    async getRoutes() {
      const res = await getRoutes();
      this.routes = res.data;
    },
    async getRoles(roleViewModel) {
      this.loading = true;
      const res = await getRoleList(roleViewModel);
      if (res.data) {
        this.roleViewModel.total = res.data.Total;
      }
      this.rolesList = res.data.Items;
      this.loading = false;
    },
    queryRole() {
      this.roleViewModel.page = 1;
      this.getRoles(this.roleViewModel);
    },
    refresh() {
      this.roleViewModel.RoleName = '';
      this.roleViewModel.page = 1;
      this.queryRole();
    },
    async getUserList(userViewModel) {
      this.loading = true;
      const res = await getUserList(userViewModel);
      if (res.data) {
        this.userViewModel.total = res.data.TotalCount;
      }
      this.userList = res.data.UserItems;
      this.loading = false;
    },
    queryUser() {
      this.userViewModel.page = 1;
      this.getUserList(this.userViewModel);
    },
    refreshUser() {
      this.userViewModel.UserName = '';
      this.userViewModel.LoginName = '';
      this.userViewModel.MobilePhone = '';
      this.userViewModel.OrgCode = '';
      this.userViewModel.OrgName = '';
      this.userViewModel.page = 1;
      this.getUserList(this.userViewModel);
    },
    sortChange(data) {
      const { prop, order } = data
      this.userViewModel.OrderBy = prop
      if (prop == null || prop == "")
        this.userViewModel.OrderBy = "UserID"
      if (order === 'ascending') {
        this.userViewModel.SortDir = 'asc'
      } else {
        this.userViewModel.SortDir = 'desc'
      }
      this.queryUser()
    },
    lastPage(val) {
      this.userViewModel.page = val;
    },
    nextPage(val) {
      this.userViewModel.page = val;
    },
    handleSizeChange(val) {
      this.userViewModel.pageSize = val;
      this.getUserList(this.userViewModel);
    },
    handleCurrentChange(val) {
      this.userViewModel.page = val
      this.getUserList(this.userViewModel)
    },
    rolesetting(scope) {
      this.$router.push("/sys/rolesetting/" + scope.row.id);
    },
    addSubNode(scope) { //添加子节点
      this.role = Object.assign({}, defaultRole)
      this.role.ParentID = scope.row.id
      this.role.ParentName = scope.row.RoleName
      this.role.MenuIdList = scope.row.FullMenuIdList
      this.role.Type = this.activeName
      this.$nextTick(() => {
        this.$refs['role'].clearValidate() //清空上次的错误验证提示
        // this.$refs.tree.setCheckedKeys(this.role.MenuIdList);
      })
      this.dialogType = 'new';
      this.dialogVisible = true;
    },
    handleUser(scope) {
      this.dialogUserVisible = true
      this.$nextTick(() => {
        this.$refs.multipleTable.clearSelection();
      });
      getRoleUser(scope.row.id).then(res => {
        if (res.data && res.data.length > 0)
          this.multipleSelection = res.data
        this.toggleSelection(this.multipleSelection)
      })
      this.role = deepClone(scope.row);
    },
    async confirmRoleUser() {
      await handleRoleUser({ RoleId: this.role.id, Users: this.multipleSelection })
      this.$notify({
        title: "成功",
        type: "success",
        message: "操作成功!"
      });
      this.dialogUserVisible = false
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(val)// list<user>
    },
    toggleSelection(rows) {
      this.$refs.multipleTable.clearSelection();
      if (rows) {
        rows.forEach(row => {
          var p = this.userList.filter(u => u.UserId == row)[0]
          this.$refs.multipleTable.toggleRowSelection(p, true);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    addTopNode() {
      this.model = Object.assign({}, defaultModel)
      this.model.parentId = ""
      this.model.parentName = "/"
      this.$nextTick(() => {
        this.$refs['model'].clearValidate() //清空上次的错误验证提示
      })
      this.dialogMenuVisible = true;
    },
    async confirmModel() {
      //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
      var v;
      this.$refs['model'].validate(valid => {
        v = valid;
      });
      if (!v) {
        return false;
      }
      var res = await addMenu(this.model)
      if (res.code == 200) {
        this.dialogMenuVisible = false;
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
        this.getPlatformList()
      } else {
        this.$notify({
          title: "失败",
          type: "error",
          message: "操作失败"
        });
      }
    },
    handleAddRole() {
      this.role = Object.assign({}, defaultRole);
      this.role.ParentName = this.tabs.filter(z => z.code == this.activeName)[0].title
      this.role.Type = this.activeName
      // if (this.$refs.tree) {
      //   this.$refs.tree.setCheckedKeys([]);
      // }
      this.dialogType = "new";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs['role'].clearValidate() //清空上次的错误验证提示
      })
    },
    handleEdit(scope) {
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.role = deepClone(scope.row);
      this.$nextTick(() => {
        this.$refs['role'].clearValidate() //清空上次的错误验证提示
        // this.$refs.tree.setCheckedKeys(this.role.MenuIdList);
      });
    },
    handleDelete({ $index, row }) {
      if (row.children && row.children.length > 0) {
        this.$notify({
          title: "提示",
          message: "请先删除下面的子节点!",
          type: "warning",
          duration: 3000
        });
        return false;
      }
      this.$confirm("确认删除角色?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await deleteRole(row.id);
          this.$notify({
            title: "成功",
            type: "success",
            message: "操作成功!"
          });
          this.queryRole();
        })
        .catch(err => {
          console.error(err);
        });
    },
    getCheckedKeys() {
      return this.$refs.tree.getCheckedKeys();
    },
    async confirmRole(formName) {
      //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
      var v;
      this.$refs[formName].validate(valid => {
        v = valid;
      });
      if (!v) {
        return false;
      }
      const isEdit = this.dialogType === "edit";

      // // 获取选中节点id
      // const checkedKeys = this.getCheckedKeys();
      // this.role.MenuIdList = checkedKeys;

      // // 获取半选中节点id
      // const halfkeys = this.$refs.tree.getHalfCheckedKeys();
      // this.role.HalfMenuIdList = halfkeys;

      if (isEdit) {
        await updateRole(this.role);
      } else {
        await addRole(this.role)
        this.roleViewModel.page = 1
      }
      this.queryRole();
      this.dialogVisible = false;
      this.$notify({
        title: "成功",
        type: "success",
        message: "操作成功!"
      });
    }
  }
};
</script>
